<script setup>
import { getRandomColor, getPolygonDimensions, resizeCallback } from "@/utils/index"
import { ref, onMounted } from "vue"

const canvasRef = ref()
const ctxSave = ref(null)
const data = ref([])
const colorArr = ["#e60013", "#fff100", "#e5803c", "#4978b0"]

onMounted(() => {
  ctxSave.value = canvasRef.value.getContext("2d")
  ctxSave.value.strokeStyle = "rgba(59, 50, 40,1)"
  ctxSave.value.lineWidth = 1

  const arr = window.localStorage.getItem("test") ?? ""
  if (arr) {
    data.value = JSON.parse(arr)
    init()
  }
  // 添加点击事件监听器
  window.addEventListener("resize", resizeCallback(1280, 608))
  resizeCallback(1280, 608)
})

const init = () => {
  data.value.map((item) => {
    canvasFill(item.ponitArr, item.color, item.houseName)
  })
}

const canvasFill = (pointArr, color, houseName) => {
  ctxSave.value.clearRect(0, 0, ctxSave.value.width, ctxSave.value.height)
  ctxSave.value.beginPath()
  if (pointArr.length > 1) {
    ctxSave.value.moveTo(pointArr[0].x, pointArr[0].y)
    for (var i = 1; i < pointArr.length; i++) {
      ctxSave.value.lineTo(pointArr[i].x, pointArr[i].y)
    }
    ctxSave.value.fillStyle = getRandomColor(colorArr) + "B3" //填充颜色
    ctxSave.value.fill()
    ctxSave.value.stroke() //绘制

    const dimensions = getPolygonDimensions(pointArr)
    canvasText(houseName, { x: dimensions.minX, y: dimensions.minY }, dimensions)
  }
}
//绘制文字
const canvasText = (text, point, dimensions) => {
  ctxSave.value.textAlign = "center" //设置文本对齐方式
  ctxSave.value.textBaseline = "middle" //文本基线

  ctxSave.value.fillStyle = "#000" //字体颜色
  ctxSave.value.font = "italic bold 16px Arial" // 设置字体样式、粗细和大小
  const x = point.x + dimensions.width / 2
  const y = point.y + dimensions.height / 2
  ctxSave.value.fillText(text, x, y)
}
</script>

<template>
  <div class="diy-full-screen-container">
    <div class="screen-container">
      <canvas id="canvasSave2" ref="canvasRef" width="1280" height="608"></canvas>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.diy-full-screen-container {
  width: 100%;
  height: 100%;
  overflow: hidden;
  transform-origin: center;
  transform: translate(-50%, -50%) scale(1);
  position: absolute;
  left: 50%;
  top: 50%;
}

.screen-container {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}

#canvasSave2 {
  background: url("@/assets/table5.png") no-repeat top center;
  background-size: contain;
}
</style>
